<!--  -->
<template>
  <div class>
    <!-- 面包屑导航栏 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>参数管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区 -->
    <el-card>
      <!-- alert警告组件 -->
      <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" show-icon></el-alert>
      <el-row class="mt10">
        选择商品分类：
        <el-cascader
          :options="categoryLists"
          v-model="cascaderIds"
          :props="catProps"
          @change="handleCascaderChange"
        ></el-cascader>
      </el-row>
      <!-- tabs选项卡 -->
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="only">
          <el-button type="primary" size="mini" @click="addParmas" :disabled="isDisabled">添加参数</el-button>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="many">
          <el-button type="primary" size="mini" @click="addParmas" :disabled="isDisabled">添加属性</el-button>
        </el-tab-pane>
      </el-tabs>
      <el-table :data="paramsData" border class="mt15">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-tag
              class="m7"
              closable
              v-for="(item,index) in scope.row.attr_vals"
              :key="index"
              @close="removeValsTag(scope.row,index)"
            >{{item}}</el-tag>
            <el-input
              v-if="scope.row.isShowInput"
              v-model.trim="scope.row.inputValue"
              ref="saveTagInput"
              size="small"
              style="width:100px"
              @keyup.enter.native="handleInputConfirm(scope.row)"
              @blur="handleInputConfirm(scope.row)"
            ></el-input>
            <el-button v-else size="small" @click="showInput(scope.row)">+ New Tag</el-button>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="attr_name" :label="parmasTitle"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="deleteCategory(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- dirlog -->
    <!-- 添加动态参数/静态属性dirlog -->
    <el-dialog
      :title="activeTab==='only'?'添加动态参数':'添加静态属性'"
      :visible.sync="addParamsDialogVisible"
      width="50%"
      @close="clearAddParamsForm"
    >
      <el-form :model="addParamsForm" :rules="rules" ref="addParamsForm" label-width="100px">
        <el-form-item :label="parmasTitle" prop="attr_name">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveAddParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）

export default {
  name: 'goodsParams',
  components: {},
  data() {
    return {
      categoryLists: [],
      cascaderIds: [],
      catProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      activeTab: 'only',
      paramsData: [],
      addParamsDialogVisible: false,
      addParamsForm: { attr_name: '' },
      attrVals: [],
      editTagInputVisible: false,
      editTagInputValue: '',
      rules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    parmasTitle() {
      return this.activeTab === 'only' ? '参数名称' : '属性名称'
    },
    isDisabled() {
      return this.cascaderIds.length !== 3
    }
  },
  //监控data中的数据变化
  watch: {},
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    //获取级联数据
    this.getCategoryLists()
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  methods: {
    async getCategoryLists() {
      let { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.categoryLists = res.data
    },
    async handleCascaderChange() {
      if (this.cascaderIds.length === 3) {
        let { data: res } = await this.$http.get(
          `categories/${this.cascaderIds[2]}/attributes`,
          {
            params: { sel: this.activeTab }
          }
        )
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.paramsData = res.data
        this.paramsData.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
          this.$set(item, 'isShowInput', false)
          this.$set(item, 'inputValue', '')
        })
      }
    },
    handleTabClick() {
      this.handleCascaderChange()
    },
    deleteCategory(rowInfo) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          let { data: res } = await this.$http.delete(
            `categories/${rowInfo.cat_id}/attributes/${rowInfo.attr_id}`
          )
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
          this.$message.success(res.meta.msg)
          this.handleCascaderChange()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    addParmas() {
      this.addParamsDialogVisible = true
    },
    saveAddParams() {
      this.$refs.addParamsForm.validate(async valid => {
        if (!valid) return

        let { data: res } = await this.$http.post(
          `categories/${this.cascaderIds[2]}/attributes`,
          {
            attr_name: this.addParamsForm.attr_name,
            attr_sel: this.activeTab
          }
        )
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.handleCascaderChange()
        this.addParamsDialogVisible = false
      })
    },
    clearAddParamsForm() {
      this.$refs.addParamsForm.resetFields()
    },
    async removeValsTag(rowInfo, index) {
      rowInfo.attr_vals.splice(index, 1)
      let { data: res } = await this.$http.put(
        `categories/${rowInfo.cat_id}/attributes/${rowInfo.attr_id}`,
        {
          attr_name: rowInfo.attr_name,
          attr_sel: rowInfo.attr_sel,
          attr_vals: rowInfo.attr_vals.join(' ')
        }
      )
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
    },
    async handleInputConfirm(rowInfo) {
      if (rowInfo.inputValue.length === 0) return (rowInfo.isShowInput = false)
      rowInfo.attr_vals.push(rowInfo.inputValue)
      let { data: res } = await this.$http.put(
        `categories/${rowInfo.cat_id}/attributes/${rowInfo.attr_id}`,
        {
          attr_name: rowInfo.attr_name,
          attr_sel: rowInfo.attr_sel,
          attr_vals: rowInfo.attr_vals.join(' ')
        }
      )
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      rowInfo.inputValue = ''
      rowInfo.isShowInput = false
    },
    showInput(rowInfo) {
      rowInfo.isShowInput = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    }
  }
}
</script>
<style scoped>
</style>